<?php

class ProjectController extends Controller
{

	/**
	 * 项目列表
	 */
	public function actionIndex()
	{
		$projects = array();
		$user = Yii::app()->user->getModel(); /* @var $user User */
		foreach (Yii::app()->pf->getAll(true) as $tmp) {
			if ($user->hasAccess($tmp['name'])) {
				$projects[] = $tmp;
			}
		}
		$dataProvider = new CArrayDataProvider($projects, array(
			'pagination' => false,
			'sort' => false,
		));
		$this->render('index', array(
			'gridDataProvider' => $dataProvider,
		));
	}

	/**
	 * Suggest Terms
	 */
	public function actionSuggest($term)
	{
		$xs = Yii::app()->pf->get($this->projectName);
		$terms = array();
		$term = trim($term);
		if ($term !== '' && strpos($term, ':') === false) {
			try {
				$terms = $xs->search->getExpandedQuery($term);
			} catch (Exception $e) {
				
			}
		}
		header('Content-Type: application/json; charset=utf-8');
		echo CJSON::encode($terms);
		Yii::app()->end();
	}

	/**
	 * Crontab Task
	 */
	public function actionTask()
	{
		$model = new TaskForm();
		if (Yii::app()->request->isPostRequest && isset($_POST['TaskForm'])) {
			$model->attributes = $_POST['TaskForm'];
			if ($model->save()) {
				Yii::app()->user->setFlash('success', '任务请求已经提交并保存！');
			} else {
				Yii::app()->user->setFlash('error', '出错了：' . $model->getError('status'));
			}
		} else {
			Yii::app()->user->setFlash('warning', '小提示：计划任务是异步定时处理的，请耐心等候！');
		}
		$this->render('task', array('model' => $model));
	}

	/**
	 * 搜索日志
	 */
	public function actionLog()
	{
		$model = new LogModel($this->projectName);
		$q = Yii::app()->request->getParam('q', null);
		$dataProvider = new DocDataProvider($model, array(
			'query' => $q,
		));
		$this->render('log', array(
			'gridDataProvider' => $dataProvider,
			'q' => $q,
		));
	}

	/**
	 * 日志删除
	 * @param string $body words to be removed
	 */
	public function actionLogDelete($body)
	{
		$model = new LogModel($this->projectName);
		$model->deleteByPk($body);
	}

	/**
	 * 日志添加
	 */
	public function actionLogAdd()
	{
		$model = new LogAddForm();
		$user = Yii::app()->user; /* @var $user WebUser */
		if (Yii::app()->request->isPostRequest) {
			$logModel = new LogModel($this->projectName);
			$model->attributes = $_POST['LogAddForm'];
			if ($model->validate() && $model->save($logModel->getXS())) {
				$logModel->delRemovedCache($model->word);
				$user->setFlash('success', '搜索日志添加成功，稍后即可在列表中看到。');
				$this->refresh();
			}
			$user->setFlash('error', $model->getFirstError());
		} else {
			if (!$user->hasFlash('success')) {
				$user->setFlash('info', '对于已存在的搜索词，可以通过添加来增加它的搜索次数。');
			}
		}
		$this->render('log_add', array('model' => $model));
	}

	/**
	 * 热门搜索
	 * @param $type hotquery type
	 */
	public function actionHot($type = null)
	{
		$model = new LogModel($this->projectName);
		$typeOptions = $model->typeOptions();
		if ($type === null || !isset($typeOptions[$type])) {
			$type = key($typeOptions);
		}
		$q = $type . ':1';
		$dataProvider = new DocDataProvider($model, array(
			'query' => $q,
		));
		$this->render('hot', array(
			'gridDataProvider' => $dataProvider,
			'typeOptions' => $typeOptions,
			'type' => $type,
		));
	}

	/**
	 * 同义词列表、添加、导入
	 */
	public function actionSynonym()
	{
		$model = new SynonymModel($this->projectName);
		// add or import
		if (Yii::app()->request->isPostRequest) {
			try {
				if (isset($_POST['import'])) {
					if ($model->import() === true) {
						Yii::app()->user->setFlash('success', '导入成功，稍后<a href="javascript:location.reload()">刷新</a>即可看到');
						$this->refresh();
					}
				} else {
					$model->attributes = $_POST['SynonymModel'];
					if ($model->save()) {
						Yii::app()->user->setFlash('success', '添加成功，稍后<a href="javascript:location.reload()">刷新</a>即可看到');
						$this->refresh();
					}
				}
			} catch (XSException $e) {
				Yii::app()->user->setFlash('error', '操作失败：' . $e->getMessage());
			}
		}
		// list
		try {
			$page = max(1, Yii::app()->request->getParam('page', 1));
			$limit = CPagination::DEFAULT_PAGE_SIZE;
			$offset = $limit * ($page - 1);
			$list = $model->findAll($limit, $offset);
		} catch (XSException $e) {
			if ($e->getCode() === CMD_ERR_NODB) {
				$list = array();
			} else {
				throw new CHttpException(500, $e->getMessage());
			}
		}
		$dataProvider = new CArrayDataProvider($list, array(
			'sort' => false,
			'pagination' => false,
		));
		$this->render('synonym', array(
			'gridDataProvider' => $dataProvider,
			'model' => $model,
			'hasNext' => count($list) === $limit,
			'hasPrev' => $page > 1,
			'page' => $page,
		));
	}

	/**
	 * 同义词删除
	 */
	public function actionSynonymDelete($word, $synonym)
	{
		$model = new SynonymModel($this->projectName);
		$model->word = $word;
		$model->synonym = $synonym;
		$model->delete();
	}

	/**
	 * 同义词导出
	 */
	public function actionSynonymExport()
	{
		$content = '';
		try {
			$model = new SynonymModel($this->projectName);
			$words = $model->findAll(0, 0);
			foreach ($words as $word) {
				if ($word['isRemoved']) {
					continue;
				}
				$content .= self::csvQuote($word['word']) . ',' . self::csvQuote($word['synonym']) . "\r\n";
			}
		} catch (XSException $e) {
			$content = '';
		}
		// output file
		$filename = $this->projectName . '_synonyms.csv';
		header('Content-Disposition: attachment; filename="' . $filename . '"');
		header('Content-Type: text/csv');
		echo $content;
		Yii::app()->end();
	}

	/**
	 * 自定义词库
	 */
	public function actionDict()
	{
		try {
			$index = Yii::app()->pf->get($this->projectName)->index; /* @var $index XSIndex */
			if (Yii::app()->request->isPostRequest) {
				$content = trim(Yii::app()->request->getPost('content', ''));
				$index->setCustomDict($content);
				Yii::app()->user->setFlash('success', '自定义词库保存成功');
				$this->refresh();
			} else {
				$content = trim($index->getCustomDict());
				if ($content === '') {
					$content = file_get_contents(Yii::getPathOfAlias('application.data.dict_user') . '.txt');
				}
			}
			$this->render('dict', array('content' => $content));
		} catch (XSException $e) {
			throw new CHttpException(500, $e->getMessage());
		}
	}

	/**
	 * 项目结构
	 */
	public function actionSchema()
	{
		$xs = Yii::app()->pf->get($this->projectName);
		$dataProvider = new CArrayDataProvider(array_values($xs->getAllFields()), array(
			'pagination' => false,
			'sort' => false,
		));
		$this->render('schema', array(
			'gridDataProvider' => $dataProvider,
		));
	}

	/**
	 * 创建项目
	 */
	public function actionCreate()
	{
		$this->actionChange(true);
	}

	/**
	 * 修改项目配置
	 */
	public function actionChange($create = false)
	{
		$model = new SchemaForm();
		if (Yii::app()->request->isPostRequest) {
			$model->attributes = $_POST['SchemaForm'];
			$model->fields = $_POST['FieldForm'];
			if ($model->validate()) {
				try {
					Yii::app()->pf->save($model->projectName, $model->toIniContent(), $create);
					Yii::app()->user->setFlash('success', "项目配置文件已成功保存");
					if ($create) {
						$this->redirect(array('project/change', 'project' => $model->projectName));
					}
				} catch (CException $e) {
					$model->addError('projectName', $e->getMessage());
				}
			}
		} else {
			if ($create) {
				$nf = Yii::app()->request->getParam('nf', 0);
				$model->addEmptyField(min(50, max(3, $nf)));
				$model->projectName = Yii::app()->request->getParam('name', '');
			} else {
				Yii::app()->user->setFlash('info', '1. 如果您想删除某一个字段，直接将该字段名清空，再保存即可 <br/> 2. 修改项目结构很可能会导致搜索结果不正确，须重建索引！！');
				$xs = Yii::app()->pf->get($this->projectName);
				$model->initFromXS($xs);
			}
		}
		$model->addEmptyField(max(1, 3 - count($model->getFields())));
		// render form
		$this->render('change', array(
			'model' => $model,
			'create' => $create,
		));
	}

	private static function csvQuote($value)
	{
		return strpos($value, ',') === false ? $value : '"' . str_replace('"', '\\"', $value) . '"';
	}
}
